import { Card, Button, Form, Input, message } from 'antd'
import './index.scss'
import logo from '@/assets/logo.png'
import { fetchLogin } from '@/store'
import { useDispatch } from 'react-redux'
import { useNavigate } from 'react-router-dom'

const Login = () => {
    const dispatch = useDispatch()
    const navigate = useNavigate()
    // 1.定义表单校验规则
    const rules = {
        phone: [
            {
                required: true,
                message: '请输入手机号'
            },
            {
                pattern: /^1[3-9]\d{9}$/,
                message: '请输入正确的手机号格式'
            }
        ],
        authCode: [
            {
                required: true,
                message: '请输入验证码'
            },
            {
                pattern: /^\d{6}$/,
                message: '验证码格式错误'
            }
        ]
    }
    // 2.收集数据，提交表单
    const onFinish = async (values) => {
        const data = {
            mobile:values.phone,
            code: values.authcode
        }
        await dispatch(fetchLogin(data))

        // 提示信息
        message.success('登录成功!')
        // 跳转
        navigate('/')
    }
    return (
        <div className="login">
            {/* 表单结构 */}
            <Card
                // 标题
                title={<img src={logo} alt='极客园' />}
                bordered={false}
            >
                {/* 内容 */}
                <Form  onFinish={onFinish} validateTrigger="onChange">
                    <Form.Item name="phone" rules={rules.phone}>
                        <Input placeholder='请输入手机号' />
                    </Form.Item>
                    <Form.Item name="authcode" rules={rules.authCode}>
                        <Input placeholder='请输入验证码' />
                    </Form.Item>
                    <Form.Item>
                        <Button type="primary" htmlType='submit' block size="large">登录</Button>
                    </Form.Item>
                </Form>
            </Card>
        </div>
    )

}

export default Login